package com.janko.springbootbase.controller.delay;

import redis.clients.jedis.*;

import java.util.Calendar;
import java.util.Set;

/**
 * @Description redis方式的延时任务
 * @Author nieyankang
 * @Version 1.0
 * @date 2020-10-9 16:41:35
 */
public class Delay_Redis {
    /**
     * 利用redis的zset,zset是一个有序集合，每一个元素(member)都关联了一个score,通过score排序来取集合中的值
     * [zset常用命令](http://redisdoc.com/sorted_set/)
     * 添加元素:**ZADD key score member [[score member] [score member] ...]**
     * 按顺序查询元素:**ZRANGE key start stop [WITHSCORES]**
     * 查询元素score:**ZSCORE key member**
     * 移除元素:**ZREM key member [member ...]**
     */
    private static final String ADDR = "127.0.0.1";
    private static final int PORT = 6379;
    private static Jedis jedis;
    //    private static JedisPool jedisPool = new JedisPool(ADDR, PORT);
//    Jedis  jedis = new Jedis(ADDR, 6379);
    public static Jedis getJedis(){
        if(null==jedis){
            jedis=new Jedis(ADDR,PORT);
            jedis.auth("123456");
        }
        return jedis;
    }

    //生产者,生成5个订单放进去
    public void productionDelayMessage() {
        for (int i = 0; i < 5; i++) {
            //延迟3秒
            Calendar cal1 = Calendar.getInstance();
            cal1.add(Calendar.SECOND, 3);
            int second3later = (int) (cal1.getTimeInMillis() / 1000);
            Delay_Redis.getJedis().zadd("OrderId", second3later, "OID0000001" + i);
            System.out.println(System.currentTimeMillis() + "ms:redis生成了一个订单任务：订单ID为" + "OID0000001" + i);
        }
    }

    //消费者，取订单
    public void consumerDelayMessage() {
        Jedis jedis = Delay_Redis.getJedis();
        while (true) {
            Set<Tuple> items = jedis.zrangeWithScores("OrderId", 0, 1);
            if (items == null || items.isEmpty()) {
                System.out.println("当前没有等待的任务");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                continue;
            }
            int score = (int) ((Tuple) items.toArray()[0]).getScore();
            Calendar cal = Calendar.getInstance();
            int nowSecond = (int) (cal.getTimeInMillis() / 1000);
            if (nowSecond >= score) {
                String orderId = ((Tuple) items.toArray()[0]).getElement();
                Long num = jedis.zrem("OrderId", orderId);
                if (num != null && num > 0) {
                    System.out.println(System.currentTimeMillis() + "ms:redis消费了一个任务：消费的订单OrderId为" + orderId);
                }
            }
        }
    }
}
